package fr.lille.inria.adam.lifl.EcoGardeInventory.Activities;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import fr.lille.inria.adam.lifl.EcoGardeInventory.R;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.LocationService;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.SIGObservation;
import fr.lille.inria.adam.lifl.EcoGardeInventory.scrapper.User;
import fr.lille.inria.adam.lifl.EcoGardeInventory.scrapper.cache.CachedClientSIGService;

public class MainActivity_Registration extends BuildObservationActivity {
	protected ServiceConnection clientLocationServConn = null;
	protected boolean isClientLocationBounded = false;
	
	private Button submitButton=null;
	private TextView mTextViewUsername = null, mTextViewPassword = null;
	
	// utilisé lorsque la connexion au service est en retard
	private transient User awaitedUser = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// #region invocation de la vue et Binding
		setContentView(R.layout.main_registration);
		setTitle("Bienvenue sur l'application de l'EcoGarde de Lille"); //TODO: Utiliser strings.xml

		// Champs login et mot de passe
		mTextViewUsername = (TextView) findViewById(R.id.username);
		mTextViewUsername.setMovementMethod(new ScrollingMovementMethod());
		mTextViewPassword = (TextView) findViewById(R.id.password);
		mTextViewPassword.setMovementMethod(new ScrollingMovementMethod());

		// Comportement attaché au bouton d'envoi
		submitButton = (Button) findViewById(R.id.SubmitUsernameAndPassword);
		submitButton.setOnClickListener(new OnClickListener() {
			public void onClick(View actuelView) {
				final String username = mTextViewUsername.getText().toString();
				final String password = mTextViewPassword.getText().toString();
				
				if (username.length() == 0) {
					Toast.makeText(MainActivity_Registration.this, "Veillez entrer votre identifiant", Toast.LENGTH_SHORT).show();
				} else {
					if (password.length() == 0) {
						Toast.makeText(MainActivity_Registration.this, "Veillez entrer votre mot de passe", Toast.LENGTH_SHORT).show();
					} else {
						user = new User();
						user.login = username;
						user.password = password;
						
						if ((clientBinder != null) && (clientBinder.isBinderAlive())) {
							clientBinder.setUser(user);
							
							// On v�rifiera plus tard, l� on change d'activit�
							startNextActivity();
						} else {
							// Pas de connexion? Le listener de connexion au service s'en
							// chargera
							awaitedUser = user;
						}
					}
				}
			}

		});
		// #endregion Binding UI Ctrl
		
		this.initializeLocationServConn();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		Intent locationIntent = new Intent(this, LocationService.class);
		isClientLocationBounded = bindService(locationIntent, this.clientLocationServConn, BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (isClientLocationBounded) { unbindService(clientLocationServConn); }
	}
	
	private void startNextActivity() {
		Intent selectObsIntent = new Intent(getApplicationContext(), SelectStringEntryOnList.class);
		selectObsIntent.putExtra("SIG_OBSERVATION", new SIGObservation());
		selectObsIntent.putExtra("SIG_USER", user);
		selectObsIntent.putExtra(SelectStringEntryOnList.extraIntentKey_STEP, SelectStringEntryOnList.TYPE_OBSERVATEUR);
		startActivity(selectObsIntent);
	}
	
	protected ServiceConnection initializeClientSIGServConn() {
		return new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) { }
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				if (clientBinder.isObsoleteCache()) {
					clientBinder.refreshCache(new Messenger(new OnCacheRefresh()));
					submitButton.setClickable(false);
					submitButton.setText("Mise à jour. Patientez.");
				}
				
				if (awaitedUser != null) {
					clientBinder.setUser(awaitedUser);
					awaitedUser = null; //Consume
					startNextActivity();
				} else {
					// Rien � faire :/
				}
			}
		};
	}
	
	private class OnCacheRefresh extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch (msg.what) {
			case CachedClientSIGService.SP_REFRESH_STATUS_DONE:
				submitButton.setText("Connexion");
				submitButton.setClickable(true);
				break;
			case CachedClientSIGService.SP_REFRESH_STATUS_PROGRESS:
				submitButton.setText(String.format("Mise à jour: %d%%", (Integer) msg.obj));
				break;

			default:
				break;
			}
			
			
		}
	}
	
	private void initializeLocationServConn() {
		this.clientLocationServConn = new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) {
				Log.d("MainActivity", "La localisation s'est déconnectée");
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				Log.d("MainActivity", "La localisation s'est connectée");
			}
		};
	}
}
